package sqcon.sql;

import sqcon.util.StringParsingException;
import sqcon.util.StringTokenParser;

import java.util.NoSuchElementException;

public class WhereClause implements Clause {

	private static final ClauseType type = ClauseType.WHERE;
	
	private ConditionTreeNode conditionTree;
	
	public WhereClause(ConditionTreeNode conditionTree){
		this.conditionTree = conditionTree;
	}
	
	public WhereClause(String clauseString) throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(clauseString, true);
		try{
			if(!stp.nextToken().equalsIgnoreCase(ClauseType.WHERE.toString())){
				throw new ConstructSqlException("Where Clause Parsing Error");
			}
			
			setWhereContent(stp.getRest());
		}catch(StringParsingException e){
			throw new ConstructSqlException("Where Clause Parsing Error");
		}catch(NoSuchElementException nsee){
			throw new ConstructSqlException("Where Clause Parsing Error");
		}
	}
	
	@Override
	public String printString() {
		return "WHERE " + conditionTree.printString();
	}

	@Override
	public ClauseType getClauseType() {
		return type;
	}
	
	public ConditionTreeNode getConditionTree(){
		return conditionTree;
	}
	
	//TODO implement this method
	private void setWhereContent(String contentStr) 
			throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(contentStr, true);
		conditionTree = null;
		
		//TODO replace all these code with parseCondTree(String) method
		try{
			String comparison = "";
			while(stp.hasMoreTokens()){
				String word = stp.nextToken();
				if(LogicOperator.isLogicOperator(word)){
					ConditionTreeNode leftCondNode = 
						ComparisonNode.generateComparisonNode(comparison);
					
					LogicOperator operator = 
						LogicOperator.getLogicOperator(word);
					
					ConditionTreeNode rightCondNode = 
						parseCondTree(stp.getRest());
					
					conditionTree = new LogicalNode(operator, leftCondNode, 
							rightCondNode);
					
					break;
				}
				comparison = comparison + " " + word;
			}
			
			if(conditionTree == null){
				conditionTree = ComparisonNode.generateComparisonNode(
						comparison);
			}
			
		}catch(StringParsingException e){
			throw new ConstructSqlException("Where Clause Parsing Error");
		}
		
		//-----------------------------------------------------------------
	}
	
	//TODO implement this method
	private ConditionTreeNode parseCondTree(String condStr) 
			throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(condStr, true);
		
		try{
			while(stp.hasMoreTokens()){
				String word = stp.nextToken();
				
			}
		}catch(StringParsingException spe){
			throw new ConstructSqlException("Where Clause Parsing Error...");
		}
		return null;
	}
}
